<template>
  <div class="register-wrapper">
    <h2 class="register-title">创建账号</h2>
    <p class="register-subtitle">加入我们，悦享生活</p>

    <el-form ref="registerForm" :model="registerForm" :rules="rules" class="register-form">
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            class="custom-input">
        </el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="请设置密码"
            prefix-icon="el-icon-lock"
            class="custom-input">
        </el-input>
      </el-form-item>

      <!-- 真实姓名 -->
      <el-form-item prop="name">
        <el-input
            v-model="registerForm.name"
            placeholder="请输入真实姓名"
            prefix-icon="el-icon-user"
            class="custom-input">
        </el-input>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item prop="email">
        <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            prefix-icon="el-icon-message"
            class="custom-input">
        </el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="code">
        <div class="validate-container">
          <el-input
              v-model="registerForm.code"
              placeholder="请输入验证码"
              prefix-icon="el-icon-chat-line-round"
              class="custom-input">
          </el-input>
          <el-button
              type="primary"
              :disabled="disabled"
              class="validate-btn"
              @click="sendVerificationCode">
            {{ buttonContent }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 用户角色 -->
      <el-form-item prop="role">
        <el-select
            v-model="registerForm.role"
            placeholder="请选择用户角色"
            class="role-select">
          <el-option label="普通用户" value="USER"></el-option>
          <el-option label="商户" value="MERCHANT"></el-option>
          <el-option label="管理员" value="ADMIN"></el-option>
        </el-select>
      </el-form-item>

      <!-- 邀请码（条件显示） -->
      <el-form-item prop="invitationCode" v-if="registerForm.role === 'ADMIN'">
        <el-input
            v-model="registerForm.invitationCode"
            placeholder="请输入管理员邀请码"
            prefix-icon="el-icon-key"
            class="custom-input">
          <template slot="append">
            <el-tooltip content="请联系超级管理员获取邀请码" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </template>
        </el-input>
      </el-form-item>

      <!-- 注册按钮 -->
      <el-form-item>
        <el-button
            type="primary"
            class="register-button"
            @click="onRegister">
          注册账号
        </el-button>
      </el-form-item>

      <div class="form-footer">
        <span>已有账号？</span>
        <el-link type="primary" @click="$router.push('/login')">
          立即登录
        </el-link>
      </div>
    </el-form>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: 'Register',
  data() {
    // 验证邀请码
    const validateInvitationCode = (rule, value, callback) => {
      if (this.registerForm.role === 'ADMIN') {
        if (!value) {
          callback(new Error('请输入管理员邀请码'));
        } else if (value !== 'ADMIN666') {
          callback(new Error('邀请码不正确'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      countdown: 0,
      disabled: false,
      timer: null,
      emailCode: '',
      buttonContent: '发送验证码',
      registerForm: {
        username: '',
        password: '',
        name: '',
        email: '',
        code: '',
        role: 'USER',
        status: 1,
        invitationCode: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择用户角色', trigger: 'change' }
        ],
        invitationCode: [
          { validator: validateInvitationCode, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    sendVerificationCode() {
      if (this.disabled) return;

      if (!this.registerForm.email) {
        this.$message.error('请先输入邮箱地址');
        return;
      }

      request.get(`/email/sendEmail/${this.registerForm.email}`).then(res => {
        if (res.code === '0') {
          this.$message({
            type: 'success',
            message: "验证码已发送到您的邮箱,请查收"
          });
          console.log(res.data);
          this.emailCode = res.data;
          this.startCountdown();
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      });
    },

    startCountdown() {
      this.countdown = 60;
      this.disabled = true;
      this.buttonContent = `${this.countdown}秒后重试`;

      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
          this.buttonContent = `${this.countdown}秒后重试`;
        } else {
          clearInterval(this.timer);
          this.disabled = false;
          this.buttonContent = '发送验证码';
        }
      }, 1000);
    },

    onRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          if (String(this.registerForm.code) !== String(this.emailCode)) {
            console.log('Input code:', this.registerForm.code, 'Expected code:', this.emailCode);
            this.$message({
              type: 'error',
              message: '验证码不正确'
            });
            return;
          }

          if (this.registerForm.role === 'ADMIN' &&
              this.registerForm.invitationCode !== 'ADMIN666') {
            this.$message({
              type: 'error',
              message: '管理员邀请码不正确'
            });
            return;
          }

          request.post("/user/add", this.registerForm).then(res => {
            if (res.code === '0') {
              this.$message({
                type: 'success',
                message: "注册成功，请登录"
              });
              this.$router.push('/login');
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              });
            }
          });
        }
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
.register-wrapper {
  width: 100%;
  max-width: 400px; /* 调整最大宽度 */
  margin: 0 auto 0 -5%; /* 左侧外边距20%，向右移动 */
  padding: 0 20px;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.register-title {
  font-size: 28px;
  font-weight: 600;
  color: #E67E22;
  margin-bottom: 10px;
  text-align: center;
}

.register-subtitle {
  font-size: 15px;
  color: #666;
  margin-bottom: 30px;
  text-align: center;
}

.register-form {
  margin-top: 10px;
}

.validate-container {
  display: flex;
  gap: 16px;
}

.validate-btn {
  flex-shrink: 0;
  min-width: 120px;
  height: 44px;
  font-size: 14px;
  border-radius: 8px;
  background: linear-gradient(to right, #F39C12, #F9CA24) !important;
  border: none;
  transition: all 0.3s ease;
}

.validate-btn:hover:not(:disabled),
.validate-btn:focus:not(:disabled),
.validate-btn:active:not(:disabled) {
  background: linear-gradient(to right, #E67E22, #F39C12) !important;
  box-shadow: 0 4px 12px rgba(243, 156, 18, 0.3);
  transform: translateY(-2px);
}

.role-select {
  width: 100%;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  margin-top: 10px;
  border-radius: 8px;
  background: linear-gradient(to right, #F39C12, #F9CA24) !important;
  border: none;
  transition: all 0.3s ease;
}

.register-button:hover,
.register-button:focus,
.register-button:active {
  background: linear-gradient(to right, #E67E22, #F39C12) !important;
  box-shadow: 0 4px 12px rgba(243, 156, 18, 0.3);
  transform: translateY(-2px);
}

.form-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 25px;
  font-size: 14px;
  color: #666;
}

/* Element UI 组件样式覆盖 */
:deep(.el-input__inner) {
  height: 44px;
  line-height: 44px;
  border-radius: 8px;
  border: 1px solid #f0d5b3;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #F39C12;
  box-shadow: 0 0 0 2px rgba(243, 156, 18, 0.1);
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-input__prefix) {
  left:5px;
  color: #F39C12;
  height: 100%;
  display: flex;
  align-items: center;
}

:deep(.el-input__prefix i) {
  font-size: 16px;
  line-height: 1;
}
:deep(.el-input__prefix .el-input__icon) {
  height: auto;
}

:deep(.el-input__inner) {
  padding-left: 38px;
}

:deep(.el-select .el-input__inner) {
  padding-left: 15px;
}

:deep(.el-link.el-link--primary) {
  color: #F39C12;
}

:deep(.el-link.el-link--primary:hover) {
  color: #E67E22;
}

.el-input-group__append {
  padding: 0 10px;
  cursor: help;
}

.el-input-group__append i {
  font-size: 16px;
  color: #909399;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .register-title {
    font-size: 24px;
  }

  .register-subtitle {
    font-size: 14px;
    margin-bottom: 25px;
  }

  .validate-container {
    gap: 10px;
  }

  .validate-btn {
    min-width: 100px;
    font-size: 13px;
  }
}

:deep(.el-button--primary) {
  background-color: #F39C12;
  border-color: #F39C12;
  color: #fff;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus),
:deep(.el-button--primary:active) {
  background-color: #E67E22;
  border-color: #E67E22;
  color: #fff;
}

:deep(.el-button--primary.is-active) {
  background-color: #E67E22;
  border-color: #E67E22;
  color: #fff;
}
</style>